from django import http
from django.core.cache import cache
from django.shortcuts import render

# Create your views here.
from django.views import View
from apps.areas.models import Area
from utils.response_code import RETCODE
from utils.views import LoginRequiredJSONMixin


# 显示省市区信息
class AreaView(LoginRequiredJSONMixin,View):
    def get(self,request):
        # 获取area_id,看看是否是省信息
        area_id = request.GET.get('area_id')
        # 如果没有area_id,说明是省的信息
        if area_id is None:
            provinces = Area.objects.filter(parent__isnull=True)
            # 去缓存里读取省份信息
            pro_list=cache.get('pro')
            if pro_list is None:
                # 返回给前端一个列表
                pro_list = []
                for province in provinces:
                    pro_list.append({
                        'id':province.id,
                        'name':province.name
                    })
                # 将省份信息设置为缓存
                cache.set('pro', pro_list, 24 * 3600)
            return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok','pro_list':pro_list})
        else:
            cities_list = cache.get('cities_list%s'%area_id)
            if cities_list is None:
                try:
                    cities=Area.objects.filter(parent_id = area_id)
                except:
                    return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '出错了'})
                cities_list = []
                for city in cities:
                    cities_list.append({
                        'id':city.id,
                        'name':city.name
                    })
                cache.set('citiles_list%s'%area_id,cities_list,24*3600)
            return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok','cities':cities_list})

